<?php

namespace App\Models;

use App\Enums\DomainSource;
use App\Jobs\AliyunDomainLetsEncrypt;
use App\Models\Traits\BelongsToApplication;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Ssl extends Model
{
    use BelongsToApplication,
        SoftDeletes;

    protected $casts = [
        'type' => DomainSource::class,
        'certs' => 'json',
        'expires_at' => 'datetime',
        'expiry_date' => 'datetime',
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::created(function (Ssl $ssl) {
            $acme = app('acme');
            $domain = $ssl->ssl_domain;
            $order = $acme->createOrder([$domain]);

            $ssl->order_id = $order->getId();
            $ssl->expires_at = $order->getExpiresAt();
            $ssl->save();

            if ($ssl->type == DomainSource::ALIYUN) {
                AliyunDomainLetsEncrypt::dispatch($ssl);
            }
        });
    }

    public function aliyun(): BelongsTo
    {
        return $this->belongsTo(Aliyun::class);
    }

    public function getSslDomainAttribute(): string
    {
        if ($this->type == DomainSource::ALIYUN) {
            return $this->rr.'.'.$this->root;
        } else {
            return $this->domain;
        }
    }
}
